package my.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import my.interceptor.LoginInterceptor;
import my.model.Message;
import my.model.User;
import my.service.MessageService;

import java.util.List;

/**
 * Created by Administrator on 2017/4/13 0013.
 */
public class MessageController extends Controller {
    MessageService messageService=new MessageService();

    @Before(LoginInterceptor.class)
    public void index() {
        list();
    }

    public void list() {
        List<Message> messages = messageService.getAllMessageDetail();
        setAttr("messages",messages);
        renderFreeMarker("list-new.ftl");
    }

    public void save() {
        Message message=new Message();
        String title = getPara("message.title");
        User author = User.dao.findFirst("SELECT * FROM user where username =?",(String)getSessionAttr("username"));
        String content = getPara("message.content");
        message.setTitle(title);
        message.setAuthorId(author.getId());
        message.setContent(content);
        message.save();
        redirect("/message/list");
    }

    public void create() {
        renderFreeMarker("create-new.ftl");
    }

    public void delete(){
        int id=getParaToInt("id",-1);
        if (id!=-1) {
            messageService.deleteMessageById(id);
        }
        list();
    }
}
